package net.kqinfo.core.controller.management;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.kqinfo.common.util.scrypt.BCrypt;
import net.kqinfo.core.Constants;
import net.kqinfo.core.controller.management.condition.UserConditon;
import net.kqinfo.core.model.Organization;
import net.kqinfo.core.model.User;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.Render;

public class UserController extends Controller{
	
	private static final String LIST = "/WEB-INF/views/management/security/user/list.html";
	private static final String CREATE = "/WEB-INF/views/management/security/user/create.html";
	private static final String UPDATE = "/WEB-INF/views/management/security/user/update.html";
	private static final String LOOKUP2ORG = "/WEB-INF/views/management/security/user/lookup_org.html";
	
	public UserConditon cond;
	
	@Before(UserConditon.class)
	public void list(){
		
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		cond.buildSql(sql, paras);
		
		Page<User> userPage = User.dao.paginate(cond.getPageNumber(), cond.getPageSize(), "select *", sql.toString(), paras.toArray());
		
		setAttr("userPage", userPage);
		render(LIST);
	}
	
	public void create(){
		render(CREATE);
	}
	
	public void doCreate(){
		User user = getModel(User.class);
		user.set("password", BCrypt.hashpw(user.getStr("password"), BCrypt.gensalt(Constants.BCRYPT_LOG_ROUNDS)));
		user.set("create_time",new Date());
		user.set("org_id", getModel(Organization.class).get("id"));
		user.save();
		render(DwzRender.closeCurrentAndRefresh("users"));
	}
	
	public void update(){
		setAttr("user", getUserById());
		render(UPDATE);
	}
	
	public void doUpdate(){
		User user = getModel(User.class);
		user.set("org_id", getModel(Organization.class).get("id"));
		user.update();
		render(DwzRender.closeCurrentAndRefresh("users"));
	}
	
	public void status(){
		User user = getUserById();
		user.set("status", user.getStr("status").equals("enabled") ? "disabled":"enabled");
		user.update();
		render(DwzRender.success());
	}
	
	public void delete(){
		User.dao.deleteById(getParaToInt());
		render(DwzRender.success());
	}
	
	private User getUserById(){
		User user = null;
		long id = getParaToLong(0,-1l);
		if (id == -1l) {
			render(DwzRender.error("请选择用户！"));
		}else{
			user = User.dao.findById(id);
		}
		return user;
	}
	
	public void lookup2org(){
		setAttr("org", Organization.dao.findById(1));
		render(LOOKUP2ORG);
	}

	public UserConditon getCond() {
		return cond;
	}

	public void setCond(UserConditon cond) {
		this.cond = cond;
	}
	
}
